package com.itcode.controller;

import com.itcode.pojo.Result;
import com.itcode.pojo.User;
import com.itcode.service.UserService;
import com.itcode.utils.JwtUtil;
import com.itcode.utils.Md5Util;
import com.itcode.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
@Validated //开启参数校验
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户注册
     * @param username 姓名
     * @param password 密码
     * @return 是否注册成功
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {

        //查询用户
        User user = userService.findByUsername(username);

        if (user == null) {
            userService.register(username, password);
            return Result.success();
        } else {
            return Result.error("用户名已被占用");
        }
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return  是否登陆成功
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //根据用户名查询用户
        User loginUser = userService.findByUsername(username);
        //判断用户是否存在
        if (loginUser == null) {
            return Result.error("用户名不存在");
        }

        //判断密码是否正确
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            //生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            final String token = JwtUtil.genToken(claims);

            //把token存储到redis中
            final ValueOperations operations = redisTemplate.opsForValue();
            operations.set(token,token,12, TimeUnit.HOURS); //token既作为键，又作为值,过期时间设置为12h

            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    /**
     * 获取用户详细信息
     * @return 用户信息
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){
        //从token获取 用户名
        /*final Map<String, Object> map = JwtUtil.parseToken(token);
        final String username = (String) map.get("username");*/

        final Map<String, Object> map = ThreadLocalUtil.get(); //从线程空间获取业务数据
        final String username = (String) map.get("username"); //取出其中的username

        final User user = userService.findByUsername(username);

        return Result.success(user);
    }

    /**
     * 修改用户信息
     * @param user 用户信息
     * @return 无
     */
    @PutMapping("/update") //参数添加注解，使得我们的验证条件生效
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    /**
     * 修改用户头像
     * @param avatarUrl 用户头像
     * @return 无
     */
    @PatchMapping("/updateAvatar") //仅修改部分字段
    public Result updateAvatar(@RequestParam @URL String avatarUrl){ //表明从querystring中获取
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 修改用户密码
     * @param params 用户头像
     * @return 无
     */
    @PatchMapping("/updatePwd") //仅修改部分字段
    public Result updatePwd(@RequestBody Map<String,String > params,@RequestHeader("Authorization") String token){ //表明从querystring中获取

        // 校验参数
        final String old_pwd = params.get("old_pwd");
        final String new_pwd = params.get("new_pwd");
        final String re_pwd = params.get("re_pwd");

        if(!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) || !StringUtils.hasLength(re_pwd)){
            return Result.error("缺少必要的参数");
        }

        //原密码是否正确
        final Map<String, Object> map = ThreadLocalUtil.get();
        final String username = (String) map.get("username");
        final User loginUser = userService.findByUsername(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(old_pwd))){
            return Result.error("原密码不正确");
        }

        //校验新密码是否正确
        if(!re_pwd.equals(new_pwd)){
            return Result.error("两次输入密码不同");
        }

        userService.updatePwd(new_pwd);

        //删除redis中对应的token
        redisTemplate.opsForValue().getOperations().delete(token);

        return Result.success();
    }
}
